package com.example.webshiro.common.utils;


import com.example.webshiro.common.SpringContextHolder;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author LuoYu
 * 2021/4/11
 **/
public class RedisUtil {


    private volatile static JedisPool jedisPool;


    /**
     * <p>获取连接池</p>
     */
    private static void getPool(){
        if(jedisPool == null){
            synchronized (RedisUtil.class){
                if(jedisPool == null){
                    jedisPool = SpringContextHolder.getBean(JedisPool.class);
                }
            }
        }
    }

    /**
     * <p>获取连接客户端</p>
     * @return  客户端
     */
    public static Jedis getClient(){
        return jedisPool.getResource();
    }

    /**
     * 设置连接池
     */
    public static void initPool(){
        getPool();
    }

    /**
     * <p>校验键是否存在</p>
     * @param key  key
     * @return
     */
    public static boolean exists(String key){
        try (final Jedis client = getClient()){
            return client.exists(key);
        }

    }


    /**
     * <p>获取值</p>
     * @param key  键
     * @return    值
     */
    public static String get(String key){
        try (final Jedis client = getClient()){
            return client.get(key);
        }
    }

    /**
     * <p>设置键值</p>
     * @param key  key
     * @param o    value
     * @param exipre  过期时间 单位: 秒
     */
    public static void set(String key,String o,int exipre){
        try (Jedis client = getClient()){
            client.set(key, o);
            client.expire(key, exipre);
        }

    }


    /**
     * <p>设置键的过期时间</p>
     * @param key  key
     * @param expireTime  过期时间   单位秒
     */
    public static void setExpireTime(String key,int expireTime){
        try (Jedis client = getClient()) {
            if (exists(key)) {
                client.expire(key, expireTime);
            }
        }


    }











}
